package com.example.demo.utils;

import org.springframework.beans.BeanUtils;

import java.util.*;

public class TreeUtil {

    public List<TreeBo> buildTree(List<TestCaseNodeDo> nodeList) {
        // 最终返回结果
        List<TreeBo> treeList = new ArrayList<>();
        // 将单层的TestCaseNodeDO变成以level为key的多层map, [A1,A2,A3,B1]-> {1:[A1,B1],2:[A2],3:[A3]}
        Map<Integer, List<TestCaseNodeDo>> nodeLevelMap = new HashMap<>();
        nodeList.forEach(node -> {
            Integer level = node.getLevel();
            if (nodeLevelMap.containsKey(level)) {
                nodeLevelMap.get(level).add(node);
            } else {
                List<TestCaseNodeDo> testCaseNodes = new ArrayList<>();
                testCaseNodes.add(node);
                nodeLevelMap.put(node.getLevel(), testCaseNodes);
            }
        });

        List<TestCaseNodeDo> rootNodes = Optional.ofNullable(nodeLevelMap.get(1)).orElse(new ArrayList<>());
        rootNodes.forEach(rootNode -> treeList.add(buildNodeTree(nodeLevelMap, rootNode)));

        return treeList;
    }


    /**
     * 递归构建节点树
     * @param nodeLevelMap
     * @param rootNode
     * @return
     */
    public TreeBo buildNodeTree(Map<Integer, List<TestCaseNodeDo>> nodeLevelMap, TestCaseNodeDo rootNode) {

        TreeBo nodeTree = new TreeBo();
        BeanUtils.copyProperties(rootNode, nodeTree);
        nodeTree.setLabel(rootNode.getLabel());

        List<TestCaseNodeDo> lowerNodes = nodeLevelMap.get(rootNode.getLevel() + 1);
        if (lowerNodes == null) {
            return nodeTree;
        }

        List<TreeBo> children = Optional.ofNullable(nodeTree.getChildren()).orElse(new ArrayList<>());

        lowerNodes.forEach(node -> {
            if (node.getParentId() != null && node.getParentId().equals(rootNode.getValue())) {
                children.add(buildNodeTree(nodeLevelMap, node));
                nodeTree.setChildren(children);
            }
        });

        return nodeTree;
    }
}
